package com.mooc.ppjoke.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mooc.lib_network.ApiResponse;
import com.mooc.lib_network.ApiService;
import com.mooc.lib_network.JsonCallBack;
import com.mooc.ppjoke.R;
import com.mooc.ppjoke.data.User;
import com.google.android.material.button.MaterialButton;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private ImageView actionClose;
    private MaterialButton actionLogin;
    private Tencent tencent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        actionClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        actionLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login() {
        if(tencent==null){
            tencent = Tencent.createInstance("101794421", this);
        }
        tencent.login(this, "all", loginListener);
    }

    private void getUserInfo(QQToken qqToken,String openid,Long expires_time) {
        UserInfo userInfo = new UserInfo(this, qqToken);
        userInfo.getUserInfo(new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject response= (JSONObject) o;
                try {
                    String nickname = response.getString("nickname");
                    String figureurl_2 = response.getString("figureurl_2");
                    save(nickname, figureurl_2, openid, expires_time);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {
                Toast.makeText(LoginActivity.this, "登录失败"+uiError.toString(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCancel() {
                Toast.makeText(LoginActivity.this, "登录取消", Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void save(String nickname, String user, String openid, Long expires_time) {
         ApiService.get("/user/insert")
                .addParam("name", nickname)
                .addParam("avatar", user)
                .addParam("qqOpenId", openid)
                 .addParam("expires_time", expires_time)
                .excute(new JsonCallBack<User>() {
            @Override
            public void OnSuccess(ApiResponse<User> apiResponse) {
                if(apiResponse.body!=null){
                    QQUserManager.getInstance().saveUser(apiResponse.body);
                    finish();
                }else {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show());
                }
            }

            @Override
            public void OnError(ApiResponse<User> apiResponse) {
                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "登录失败"+apiResponse.message, Toast.LENGTH_SHORT).show());
            }
        });
    }
    IUiListener loginListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            JSONObject response = (JSONObject) o;
            try {
                String openid = response.getString("openid");
                String access_token = response.getString("access_token");
                String expires_in = response.getString("expires_in");
                long expires_time = response.getLong("expires_time");
                tencent.setOpenId(openid);
                tencent.setAccessToken(access_token, expires_in);
                QQToken qqToken = tencent.getQQToken();
                getUserInfo(qqToken, openid, expires_time);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext(), "登录失败:reason" + uiError.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(), "登录取消", Toast.LENGTH_SHORT).show();
        }
    };

    private void initView() {
        actionClose = (ImageView) findViewById(R.id.action_close);
        actionLogin = (MaterialButton) findViewById(R.id.action_login);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }

    }
}